<!--三元组详情-->
<template>
  <div class="triplet-details">
    <div class="header">
      <div class="back" @click="goBack"><i class="iconfont icon-fanhui" style="font-size: 24px;"></i></div>
      三元组-详情
    </div>
    <div v-if="infoData.orderNo" class="info-title">
      <div>{{ infoData.orderNo }} + {{ infoData.productName }}({{ infoData.productId }})</div>
      <div>{{ infoData.orderDescription }}</div>
    </div>
    <el-form :inline="true" class="search-form">
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" filterable placeholder="请选择" clearable style="width: 100px;">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="DeviceName">
        <el-input v-model="searchForm.deviceName" placeholder="请输入DeviceName" clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="DeviceSecret">
        <el-input v-model="searchForm.deviceSecret" placeholder="请输入DeviceSecret" clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="ProductKey">
        <el-input v-model="searchForm.productKey" placeholder="请输入ProductKey" clearable>
        </el-input>
      </el-form-item>
      <el-button class="btn" type="primary" size="14" @click="getList()">查询</el-button>
    </el-form>
    <div class="search">
      <div class="num-title">总数量：{{ infoData.totalAmount }}，已使用：{{ infoData.usageAmount }}</div>
      <div>
        <el-button type="primary" size="14" :disabled="!multipleSelection.length" @click="handleExport('all')">导出全部三元组</el-button>
        <el-button type="primary" size="14" :disabled="!multipleSelection.length" @click="handleExport">导出三元组</el-button>
        <el-button v-if="showBtn" type="add" size="14" class="generate" @click="handleGenerate">生成三元组</el-button>
      </div>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column label="DeviceName">
        <template slot-scope="scope">
          {{ scope.row.deviceName || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="Device Secret">
        <template slot-scope="scope">
          {{ scope.row.deviceSecret || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="ProductKey">
        <template slot-scope="scope">
          {{ scope.row.productKey || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? '已使用' : "未使用" }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="operate"
            :disabled="scope.row.status === 1"
            @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 1000]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog
      title="生成三元组"
      :visible.sync="dialogVisible"
      width="596px"
      :before-close="handleClose"
      custom-class="white-list-dialog">
      <el-form
        ref="form"
        :model="addFormData"
        :rules="rules"
        width="596px"
        label-width="80px"
        label-position="right">
        <el-form-item label="数量" prop="generateAmount">
          <el-input v-model="addFormData.generateAmount" placeholder="请输入所需数量" maxlength="6" clearable></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { devicetripletsinfo, getOrder, generate, exportTriplets, deleteDetails } from '@/api/device-identity-auth/triplet'
export default {
  name: 'tripletDetails',
  data() {
    return {
      id: '',
      tableData: [], // 列表数据
      infoData: {}, // 信息数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: true,
      dialogVisible: false,
      searchForm: {
        status: '', // 状态
        deviceName: '', // DeviceName
        deviceSecret: '', // DeviceSecret
        productKey: '' // ProductKey
      },
      multipleSelection: [], // 多选数据
      addFormData: {
        generateAmount: ''
      },
      statusList: [
        { label: '全部', value: '' },
        { label: '已使用', value: 1 },
        { label: '未使用', value: 0 }
      ],
      rules: {
        generateAmount: [
          { required: true, message: '请输入数量', trigger: 'blur' },
          { validator: this.validateNumber, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    showBtn() {
      let flag = false
      if (process.env.VUE_APP_BASE_URL === 'https://smart.miligc.com/') {
        flag = true
      } else {
        flag = false
      }
      return flag
    }
  },
  created() {
    this.id = this.$route.query.id
    this.getList()
    this.queryOrder()
  },
  methods: {
    // 所需数量校验
    validateNumber(rule, value, callback) {
      const flag = new RegExp(/^([1-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-9]\d{4}|[1-9]\d{5})$/).test(value)
      if (!flag) {
        callback(new Error('请输入最多6位的数字'))
      } else {
        callback()
      }
    },
    // 详情列表
    getList() {
      this.loading = true
      // 过滤 searchForm 中值为空的属性
      const filteredSearchForm = {}
      for (const key in this.searchForm) {
        if (this.searchForm[key] !== '') {
          filteredSearchForm[key] = this.searchForm[key]
        }
      }
      const params = {
        tripletsOrderId: this.id,
        size: this.pageSize,
        current: this.currentPage,
        ...filteredSearchForm
      }
      devicetripletsinfo(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    queryOrder() {
      const params = {
        id: this.id
      }
      getOrder(params).then(res => {
        this.infoData = res.data.data
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 返回
    goBack() {
      this.$router.push({
        path: '/device-identity-auth/triplet/index'
      })
    },
    // 全选/多选
    handleSelectionChange(val) {
      this.multipleSelection = val.map(item => item.id)
    },
    // 导出
    handleExport(type) {
      const params = {
        tripletsOrderId: type === 'all' ? this.id : '',
        idList: this.multipleSelection
      }
      exportTriplets(params).then(res => {
        this.exportBlobFile(res)
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 生成
    handleGenerate() {
      this.dialogVisible = true
    },
    // 提交生成三元组
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            generateAmount: Number(this.addFormData.generateAmount),
            tripletsOrderId: this.id
          }
          generate(params).then(res => {
            this.dialogVisible = false
            this.$refs['form'].resetFields()
            this.$message.success('生成三元组成功')
            this.getList()
            this.queryOrder()
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          return false
        }
      })
    },
    // 关闭生成三元组弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    // 删除
    handleDelete(id) {
      const params = {
        id: id
      }
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDetails(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
          this.queryOrder()
        }).catch(err => {
          this.$message.error(err.message)
        })
      }).catch(err => {})
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.triplet-details {
  .header {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 800;

    .back {
      cursor: pointer;
      margin-right: 8px;
    }
  }

  .info-title {
    font-size: 16px;
    margin: 10px 0;
    padding: 10px;
    width: max-content;
    background: rgba(39, 95, 232, 0.1);
  }

  .search-form {
    margin-top: 20px;
    .btn {
      float: right;
    }
  }

  .search {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
    margin-bottom: 24px;

    .num-title {
      width: max-content;
      background: rgba(39, 95, 232, 0.1);
      padding: 10px;
      color: #252525;
      font-size: 18px;
    }

    .generate {
      margin-left: 20px;
    }
  }

  .order-desc {
    margin-bottom: 12px;
    font-size: 18px;
    font-weight: 400;
    color: #252525;
  }
}
</style>
